<?php

/**
 * corporateindividual actions.
 *
 * @package    digitalform
 * @subpackage corporateindividual
 * @author     Saul Santiago
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class corporateindividualActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->tableColumns = ApplicationCorporateIndividualTable::TableColumns();
  }

	public function executeAjaxdata(sfWebRequest $request) {
		sfConfig::set('sf_web_debug', false);
		$this->getResponse()->setContentType('application/json');
		$this->application_corporate_individual = Doctrine::getTable('ApplicationCorporateIndividual');
		$json = $this->application_corporate_individual->fetchData($request);
		return $this->renderText($json);
	}

  public function executeAjaxNewForm(sfWebRequest $request) {
    sfConfig::set('sf_web_debug', false);
    $form = new ApplicationCorporateIndividualForm();
    return $this->renderPartial("applicationForm", array("form"=>$form));
  }

	public function executeAjaxEditForm(sfWebRequest $request) {
		$data = Doctrine_Core::getTable('ApplicationCorporateIndividual')->findOneById($request->getParameter('id'));
		$form = new ApplicationCorporateIndividualForm($data);
		return $this->renderPartial("applicationForm", array("form" => $form));
	}

  public function executeAjaxSave(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    sfConfig::set('sf_web_debug', false);
    $this->getResponse()->setContentType('application/json');
    $this->form = new ApplicationCorporateIndividualForm();
    $data_array = $this->processForm($request, $this->form, 'Added new');
    return $this->renderText(json_encode($data_array));
  }

  public function executeDatadump(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $params['from'] = ($request->getPostParameter('date_from') != '') ? $request->getPostParameter('date_from') : '';
    $params['to'] = ($request->getPostParameter('date_to') != '') ? $request->getPostParameter('date_to') : '';
    $params['ref_number'] = ($request->getPostParameter('ref_number') != '') ? $request->getPostParameter('ref_number') : '';
    $params['first_name'] = ($request->getPostParameter('first_name') != '') ? $request->getPostParameter('first_name') : '';
    $params['last_name'] = ($request->getPostParameter('last_name') != '') ? $request->getPostParameter('last_name') : '';
    $params['status'] = ($request->getPostParameter('status') != '') ? $request->getPostParameter('status') : '';

    $data = Doctrine_Core::getTable("ApplicationCorporateIndividual")->getApplicationData($params);

    if(!empty($data)) {

      header('Content-Type: text/plain');
      header('Content-Disposition: attachment;filename="ApplicationReport.xls"');
      header('Cache-Control: max-age=0');

      foreach($data as $k=>$i) {
        unset($i['updated_at']);
        if($k == 0) {
            foreach(array_keys($i) as $field) {
              echo $field."\t";
            }
            echo "\r\n";
        }
        foreach($i as $key=>$val) {
          echo $val."\t";
        }
        echo "\r\n";
      }
    }
    else {
      echo "No data to dump!";
    }
    exit();

  }

  private function processForm(sfWebRequest $request, sfForm $form, $action)
  {
    $form->bind($request->getParameter($form->getName()));

    $boolIsNew = ($form->getObject()->isNew() ? true : false );

    if ($form->isValid()) {
      unset($form['_csrf_token']);
      try {
        $application = $form->save();
        $log = new UserLogs();
        $log->setUserId($this->getUser()->getGuardUser()->getId());
        $log->setAction($action.' Corporate Individual application with Reference No.: '.$application->getRefNumber());
        $log->save();
        $data_arr = array("valid" => 'true', "message" => 'Data successfully saved!', "id" => $application->getId());
      }
      catch (Exception $exc) {
        $data_arr = array("valid" => 'false', "message" => $exc->getMessage());
      }
    }
    else {
      $errors = $form->getErrorSchema()->getErrors();
      $errorText = '';
      foreach($errors as $key=>$val) {
        $errorText .= $key.': '.$val.'|';
      }
      $data_arr = array("valid" => 'false', "message" => $errorText);
    }
    return $data_arr;
  }

  public function executeUpdate(sfWebRequest $request) {
      $this->forward404unless($request->isXmlHttpRequest());
      $formValues = $request->getParameter('application_corporate_individual');
      $this->forward404Unless($application = Doctrine_Core::getTable('ApplicationCorporateIndividual')->find(array($formValues['id']))  , sprintf('Object ApplicationCorporateIndividual does not exist (%s).', array($formValues['id'])));
      $this->getResponse()->setContentType('application/json');
      $this->form = new ApplicationCorporateIndividualForm($application);
      $data_array = $this->processForm($request, $this->form, 'Updated');
      return $this->renderText(json_encode($data_array));
  }

  public function executeDelete(sfWebRequest $request) {
      $this->forward404unless($request->isXmlHttpRequest());
      sfConfig::set('sf_web_debug', false);
      $this->getResponse()->setContentType('application/json');
      $this->forward404Unless($application = Doctrine_Core::getTable('ApplicationCorporateIndividual')->find(array($request->getParameter('id'))), sprintf('Object ApplicationCorporateIndividual does not exist (%s).', $request->getParameter('id')));
      try {
        $application->delete();
        $log = new UserLogs();
        $log->setUserId($this->getUser()->getGuardUser()->getId());
        $log->setAction('Deleted Corporate Individual application with Reference No.: '.$application->getRefNumber());
        $log->save();
        $data_arr = array("valid" => 'true', "message" => 'Data was successfully deleted!');
      }
      catch (Exception $exc) {
        $data_arr = array("valid" => 'false', "message" => $exc->getMessage());
      }
      return $this->renderText(json_encode($data_arr));
  }


}
